import dotenv

dotenv.load_dotenv()
import os
from playwright.sync_api import sync_playwright


class FaceBookNeedLogin(Exception):
    pass


class FaceBook:
    """从主页获取基本信息"""

    def __init__(self, headless=False):
        self.proxy = os.getenv("PYTHON_PROXY")
        self.headless = headless

    def __call__(self, facebook_url: str) -> str | None:
        proxy = {"server": self.proxy, "bypass": "localhost,127.0.0.1,*.local"}

        with sync_playwright() as p:
            # 启动Chromium的轻量化配置
            browser = p.chromium.launch(
                proxy=proxy,
                headless=self.headless,  # 新版无头模式（关键！资源占用大幅降低）
                args=["--no-sandbox"],
                slow_mo=100,  # 关闭延迟
            )
            context = browser.new_context(
                java_script_enabled=True,  # 仅保留必要JS
            )
            page = context.new_page()
            # url = "https://www.facebook.com/knoxreads"
            # url = "https://www.facebook.com/washoecountylibrary"
            page.goto(facebook_url)
            if "login/?next=" in page.url:
                raise FaceBookNeedLogin()
            elif 'sharer.php' in page.url:
                raise FaceBookNeedLogin()
            page.get_by_role("button", name="关闭").click()
            profile = "".join(
                page.locator("//div[@data-pagelet='ProfileTilesFeed_0']").inner_text()
            )
            return profile


if __name__ == "__main__":
    facebook = FaceBook()
    profile = facebook()
    print(profile)
